﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MDT.LifeSewagePlatform.Conmmon
{
    public class JsonWebTokenEntity
    {
        public string Issuer { get; set; }//颁发者
        public string Audience { get; set; }//接收者
        public string Secret { get; set; }//签名秘钥
        public int AccessExpiration { get; set; }//AccessToken过期时间（分钟）

        public static void SetAuthentication(IServiceCollection services, IConfiguration configuration)
        {
            #region 基础的鉴权
            var Config_TokenParameter = configuration.GetSection("JsonWebTokenConfiguration").Get<JsonWebTokenEntity>();
            services.AddAuthentication(x =>
            {

                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

            }).AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                {
                    ValidateIssuerSigningKey = true,//是否调用对签名securityToken的SecurityKey进行验证
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Config_TokenParameter.Secret)),//签名秘钥
                    ValidateIssuer = true,//是否验证颁发者
                    ValidIssuer = Config_TokenParameter.Issuer,//颁发者
                    ValidateAudience = true,//是否验证接收者
                    ValidAudience = Config_TokenParameter.Audience,//接收者
                    ValidateLifetime = true,//是否验证失效时间
                };

                x.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        // 如果过期，则把<是否过期>添加到，返回头信息中
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("Token-Expired", "true");
                        }

                        return Task.CompletedTask;
                    },
                    OnChallenge = context =>
                    {
                        context.Response.StatusCode = 401;
                        context.HandleResponse();

                        //自定义自己想要返回的数据结果，我这里要返回的是Json对象，通过引用Newtonsoft.Json库进行转换
                        var json = JsonConvert.SerializeObject(new { code = 401, msg = "未经授权!", status = false });
                        //自定义返回的数据类型
                        context.Response.ContentType = "application/json";
                        //自定义返回状态码，默认为401 我这里改成 200
                        context.Response.StatusCode = StatusCodes.Status200OK;
                        //context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                        //输出Json数据结果

                        byte[] bys = Encoding.UTF8.GetBytes(json);
                        return context.Response.Body.WriteAsync(bys, 0, bys.Length);
                    },
                    OnTokenValidated = context =>
                    {
                        return Task.CompletedTask;
                    },
                    OnForbidden = context =>
                    {
                        return Task.CompletedTask;
                    }
                };
            });
            #endregion
        }
    }
}
